import { useRequest } from 'ahooks';
import {
  message, Select, Form
} from 'antd';
import { useEffect, useState } from 'react';

import * as APIS from '../../../constants/api-constants';

const { Option, OptGroup } = Select;

interface SearchProps {
  setQuestionnaireUuid: (questionnaireUuid: string) => void,
  templateTitle: string | undefined,
  questionnaireName: string | undefined,
  isModify: boolean
}

export default ({
  setQuestionnaireUuid,
  templateTitle,
  questionnaireName,
  isModify
}: SearchProps) => {
  const [questionnaireDisable, setQuestionnaireDisable] = useState(true);
  const [templateUuid, setTemplateUuid] = useState('');
  const [
    currentTemplateValue,
    setCurrentTemplateValue
  ] = useState(templateTitle);
  const [
    currentQuestionnaireValue,
    setCurrentQuestionnaireValue
  ] = useState(questionnaireName);

  const [templateOptionList, setTemplateOptionList] = useState<
    AnswerSetting.TemplateItemOption[] | undefined
  >();
  const [questionnaireOptionList, setQuestionnaireOptionList] = useState<
    AnswerSetting.QuestionnaireItemOption[] | undefined
  >();

  /**
   * 获得template选项列表
   */
  const {
    run: requestTemplateOptionList,
    loading: templateLoading
  } = useRequest((templateName: string) => ({
    url: APIS.TEMPLATE_OPTION_LIST,
    method: 'GET',
    params: {
      title: templateName,
    }
  }), {
    debounceInterval: 1000,
    manual: true,
    onSuccess: (result) => {
      const currentTemplateOptionList = result.data;
      setTemplateOptionList(currentTemplateOptionList);
    },
    onError: () => {
      message.error('templet列表生成错误');
    },
  });

  /**
   * 获得questionnaire选项列表
   */
  const {
    run: requestQuestionnaireOptionList,
    loading: questionnaireLoading
  } = useRequest((
    currentQuestionnaireName: string,
    selectTemplateUuid: string
  ) => ({
    url: APIS.QUESTIONNAIRE_OPTION_LIST,
    method: 'GET',
    params: {
      name: currentQuestionnaireName,
      templateUuid: selectTemplateUuid,
    }
  }), {
    debounceInterval: 1000,
    manual: true,
    onSuccess: (result) => {
      const currentQuestionnaireOptionList = result.data;
      setQuestionnaireOptionList(currentQuestionnaireOptionList);
    },
    onError: () => {
      message.error('二级选项列表生成错误');
    },
  });

  useEffect(() => {
    requestTemplateOptionList('');
    if (templateTitle) {
      setQuestionnaireDisable(false);
    }
  }, []);

  return (
    <>
      <Form.Item
        label="问卷选择"
        name="templateTitle"
        rules={[{ required: true, message: '请选择问卷！' }]}
      >
        <Select
          showSearch
          disabled={isModify}
          placeholder="请选择"
          value={currentTemplateValue}
          loading={templateLoading}
          style={{ width: 350 }}
          onSelect={(
            value: string,
            option: any
          ) => {
            const { key } = option;
            setTemplateUuid(key);
            setCurrentTemplateValue(value);
            setQuestionnaireDisable(false);
            setCurrentQuestionnaireValue('');
            requestQuestionnaireOptionList('', key);
          }}
          onSearch={(templateName: string) => {
            requestTemplateOptionList(templateName);
          }}
        >
          {templateOptionList?.map(({ label, templateOption }) => (
            <OptGroup label={label} key={label}>
              {
                templateOption.map(({ title, uuid }) => (
                  <Option key={uuid} value={title}>{title}</Option>
                ))
              }
            </OptGroup>
          ))}
        </Select>
      </Form.Item>
      <Form.Item
        label="二级问卷"
        name="questionnaireName"
        rules={[{ required: true, message: '请选择二级问卷！' }]}
      >
        <Select
          showSearch
          allowClear
          value={currentQuestionnaireValue}
          disabled={questionnaireDisable || isModify}
          placeholder="请选择"
          loading={questionnaireLoading}
          style={{ width: 350 }}
          onSelect={(value: string, option: any) => {
            const { key } = option;
            setCurrentQuestionnaireValue(value);
            setQuestionnaireUuid(key);
          }}
          onSearch={(questionnaireValue: string) => {
            if (templateUuid) {
              requestQuestionnaireOptionList(
                questionnaireValue,
                templateUuid
              );
            }
          }}
        >
          {questionnaireOptionList?.map(({ name, uuid }) => (
            <Option key={uuid} value={uuid}>{name}</Option>
          ))}
        </Select>
      </Form.Item>
    </>
  );
};
